import 'package:flutter/material.dart';
import 'package:honeypotflutter/public/views/public_empty.dart';

class HLFuture<T> extends StatelessWidget {
  /// 网络请求
  final Future<T> future;

  /// 提示语
  final String remind;

  final Widget? Function(AsyncSnapshot<T> snap) snap;

  const HLFuture({
    Key? key,
    required this.future,
    required this.snap,
    this.remind = "数据加载中...",
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<T>(
        future: future,
        builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
          // 请求已结束
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              // 请求失败，显示错误
              return HLEmpty();
            } else {
              // 请求成功，显示数据
              return snap(snapshot) ?? HLEmpty();
            }
          } else {
            // 请求未结束，显示loading
            return Center(
              child: Container(
                padding: EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(color: Colors.white70),
                    SizedBox(height: 15),
                    Text(
                      remind,
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white70,
                      ),
                    )
                  ],
                ),
              ),
            );
          }
        });
  }
}
